package com.xuzhijie.pms.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Base64;

public class WechatDecryptUtil {
    public static String decryptData(String encryptedData, String sessionKey, String iv) throws Exception {
        // 添加BouncyCastleProvider支持
        Security.addProvider(new BouncyCastleProvider());

        byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
        byte[] ivBytes = Base64.getDecoder().decode(iv);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec spec = new SecretKeySpec(sessionKeyBytes, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivBytes));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);

        byte[] decrypted = cipher.doFinal(encryptedDataBytes);

        return new String(decrypted);
    }
}
